package com.sanron.sunweather.action;

import android.content.Context;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.sanron.sunweather.entity.City;
import com.sanron.sunweather.utils.CommonUtils;

/**
 * 位置服务
 *
 */
public class LocationAction {

	private LocationClient locationClient;
	private LocationAction(Context context){
		locationClient = new LocationClient(context.getApplicationContext());
	}
	
	private static LocationAction instance;
	public static LocationAction getInstance(Context context){
		if(instance==null){
			synchronized (LocationAction.class) {
				if(instance==null){
					instance = new LocationAction(context);
				}
			}
		}
		return instance;
	}
	
	public void requestLocation(final OnLocationListener onLocationListener){

		if(onLocationListener==null){
			throw new IllegalArgumentException("listener is null");
		}
		
		locationClient.registerLocationListener(new BDLocationListener() {
			@Override
			public void onReceiveLocation(BDLocation location) {
				//停止定位
				locationClient.unRegisterLocationListener(this);
				locationClient.stop();
				
				if(location.getLocType()==BDLocation.TypeNetWorkLocation){
					City city = null;
					String area = location.getDistrict();

					//定位到县/区级别
					if(area!=null && !area.trim().equals("")){
						area = area.replaceAll("县|区", "");
						city = CommonUtils.findCityByName(area);
					}
					
					//定位成功
					if(city!=null){
						onLocationListener.onLocationSuccess(city);
						return;
					}
					
					//未定位到县区级别  或是  无此县区级别天气数据
					area = location.getCity();
					if(area!=null && !area.trim().equals("")){
						area = area.replaceAll("市", "");
						city = CommonUtils.findCityByName(area);
					}
					
					//定位成功
					if(city!=null){
						onLocationListener.onLocationSuccess(city);
						return;
					}
				}
				//定位失败
				onLocationListener.onLocationFailed();
			}
		});
		LocationClientOption opt = new LocationClientOption();
		opt.setLocationMode(LocationMode.Battery_Saving);
		opt.setIsNeedAddress(true);
		locationClient.setLocOption(opt);
		locationClient.start();
	};
	
	public interface OnLocationListener{
		public void onLocationFailed();
		public void onLocationSuccess(City city);
	}
}
